package com.lou1052.core.util.serialization;

import com.lou1052.core.exception.SerializerException;
import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/10/18
 * Time: 18:03
 * To change this template use File | Settings | File Templates.
 */
public final class FastSerializerUtil {
    private FastSerializerUtil(){}

    private static final FSTConfiguration FST = FSTConfiguration.createDefaultConfiguration();

    /**
     * 序列化对象
     * @param obj
     * @return
     */
    public static  byte[] serializer(Object obj){
        return FST.asByteArray(obj);
    }

    /**
     * 反序列化对象
     * @param data
     * @param <T>
     * @return
     */
    public static <T> T deserializer(byte[] data){
        return (T)FST.asObject(data);
    }

    /**
     * 从输入流中读取对象
     * @param stream
     * @param <T>
     * @return
     */
    public static <T>T read(InputStream stream){
        try {
            FSTObjectInput in = FST.getObjectInput(stream);
            return (T)in.readObject();
        }catch (Exception e){
            throw new SerializerException(e.getMessage(),e);
        }finally {
            try {
                stream.close();
            } catch (IOException e) {
                //TODO LOG
            }
        }
    }

    /**
     * 写入对象
     * @param stream
     * @param toWrite
     */
    public static void write(OutputStream stream, Object toWrite){
        try {
            FSTObjectOutput out = FST.getObjectOutput(stream);
            out.writeObject(toWrite);
            out.flush();
        }catch (Exception e){
            throw new SerializerException(e.getMessage(),e);
        }finally {
            try {
                stream.close();
            }catch (Exception e){
                //TODO LOG
            }
        }
    }
}
